package statadminlogic

import (
	"context"
	"go.uber.org/zap"
	"navi-mumbai/common/key/dbkey"
	"navi-mumbai/common/utils"
	"navi-mumbai/common/xerr"
	"strconv"
	"time"

	"navi-mumbai/app/rpc/stat/internal/svc"
	"navi-mumbai/app/rpc/stat/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type QueryWithdrawStatLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewQueryWithdrawStatLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QueryWithdrawStatLogic {
	return &QueryWithdrawStatLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 查询提现统计
func (l *QueryWithdrawStatLogic) QueryWithdrawStat(in *pb.QueryWithdrawStatReq) (*pb.QueryWithdrawStatResp, error) {
	defer utils.RecoverPanic()

	var start, end int64
	if in.StartTime != "" {
		loc, _ := time.LoadLocation(dbkey.DateTimeZone)
		t, err := time.ParseInLocation(dbkey.DateTimeCNFormat, in.StartTime, loc)
		if err != nil {
			l.Logger.Errorf("err == ", zap.Error(err))
			return nil, xerr.NewGrpcErrCodeMsg(xerr.RequestParamError, err.Error())
		}
		start, _ = strconv.ParseInt(t.Format(dbkey.DateFormat2), 10, 64)
	}
	if in.EndTime != "" {
		loc, _ := time.LoadLocation(dbkey.DateTimeZone)
		t, err := time.ParseInLocation(dbkey.DateTimeCNFormat, in.EndTime, loc)
		if err != nil {
			l.Logger.Errorf("err == ", zap.Error(err))
			return nil, xerr.NewGrpcErrCodeMsg(xerr.RequestParamError, err.Error())
		}
		end, _ = strconv.ParseInt(t.Format(dbkey.DateFormat2), 10, 64)
	}

	var resp pb.QueryWithdrawStatResp
	var err error

	resp.WithdrawAmount, err = l.svcCtx.UserWithdrawDailyStatModel.SumAmount(l.ctx, in.PayChannelId, start, end)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, xerr.NewGrpcErrCodeMsg(xerr.DbError, err.Error())
	}

	resp.WithdrawCount, err = l.svcCtx.UserWithdrawDailyStatModel.SumSuccessFlow(l.ctx, in.PayChannelId, start, end)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, xerr.NewGrpcErrCodeMsg(xerr.DbError, err.Error())
	}

	resp.WithdrawUserCount, err = l.svcCtx.UserWithdrawDailyStatModel.SumSuccessUser(l.ctx, in.PayChannelId, start, end)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, xerr.NewGrpcErrCodeMsg(xerr.DbError, err.Error())
	}
	return &resp, nil
}
